/**
 * 研发项目分支控制器
 */

const BaseProjectController = require('./base_project_controller.js');
const ResearchProjectModel = require('../config/models_config').research_project_model;
const ResearchBranchModel = require('../config/models_config').research_project_branch_model;
const ResearchVersionModel = require('../config/models_config').research_project_version_model;
const timeUtil = require('../../../framework/helpers/time_util.js');
const LogModel = require('../config/models_config').log_model;
const dbUtil = require('../../../framework/database/db_util.js');

class ResearchBranchController extends BaseProjectController {

    /** 构造函数 */
    constructor() {
        super();
    }

    /**
     * 路由函数，根据action参数调用对应的方法
     */
    async router() {
        console.log('=== 研发项目分支控制器 ===');
        
        // 数据校验
        let rules = {
            action: 'must|string|name=操作类型',
        };
        
        // 取得数据
        let input = this.validateData(rules);
        const action = input.action;
        
        // 根据action调用不同的处理函数
        if (action === 'getBranchList') {
            return await this.getBranchList(input);
        } 
        else if (action === 'createBranch') {
            return await this.createBranch(input);
        } 
        else if (action === 'updateBranch') {
            return await this.updateBranch(input);
        } 
        else if (action === 'deleteBranch') {
            return await this.deleteBranch(input);
        } 
        else if (action === 'mergeBranch') {
            return await this.mergeBranch(input);
        } 
        else if (action === 'getBranchVersions') {
            return await this.getBranchVersions(input);
        } 
        else if (action === 'switchToVersion') {
            return await this.switchToVersion(input);
        } 
        else {
            throw new Error('未知的action参数:' + action);
        }
    }

    /**
     * 获取项目分支列表
     * @param {Object} input 请求参数
     */
    async getBranchList(input) {
        // 数据校验
        let rules = {
            projectId: 'must|string|name=项目ID',
        };
        
        // 验证输入参数
        input = this.validateData(rules, input);
        
        console.log('获取项目分支列表', input);
        
        try {
            const userInfo = await this.getUserInfo();
            
            // 查询分支列表
            const branchModel = new ResearchBranchModel();
            const where = {
                PARENT_ID: input.projectId,
                STATUS: 1 // 有效状态
            };
            
            const list = await branchModel.getList(where, 'ADD_TIME DESC');
            
            // 格式化结果
            const result = list.map(item => {
                return {
                    _id: item._id,
                    NAME: item.BRANCH_NAME,
                    DESC: item.BRANCH_DESC,
                    TYPE: item.BRANCH_TYPE,
                    PARENT_ID: item.PARENT_ID,
                    STATUS: item.BRANCH_STATUS,
                    CREATOR_ID: item.CREATOR_ID,
                    CREATOR_NAME: item.CREATOR_NAME,
                    ADD_TIME: item.ADD_TIME,
                    EDIT_TIME: item.EDIT_TIME
                };
            });
            
            // 记录系统日志
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.projectId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '获取分支列表',
                TYPE: 2, // 系统操作
                STATUS: 1, // 成功
                CONTENT: JSON.stringify({
                    projectId: input.projectId,
                    branchCount: result.length
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            return result;
        } catch (error) {
            console.error('获取项目分支列表失败:', error);
            
            // 记录系统日志
            const userInfo = await this.getUserInfo();
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.projectId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '获取分支列表',
                TYPE: 2, // 系统操作
                STATUS: 0, // 失败
                CONTENT: JSON.stringify({
                    error: error.message || error.toString()
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            throw error;
        }
    }

    /**
     * 创建项目分支
     * @param {Object} input 请求参数
     */
    async createBranch(input) {
        // 数据校验
        let rules = {
            parentId: 'must|string|name=父项目ID',
            name: 'must|string|min:2|max:50|name=分支名称',
            desc: 'string|max:200|name=分支描述',
        };
        
        // 验证输入参数
        input = this.validateData(rules, input);
        
        console.log('创建项目分支', input);
        
        // 开启事务
        const transaction = await dbUtil.startTransaction();
        
        try {
            const userInfo = await this.getUserInfo();
            
            // 检查父项目是否存在
            const projectModel = new ResearchProjectModel();
            const parentProject = await projectModel.getOne(input.parentId);
            
            if (!parentProject) {
                throw new Error('父项目不存在');
            }
            
            // 创建分支数据
            const branchModel = new ResearchBranchModel();
            const data = {
                BRANCH_NAME: input.name,
                BRANCH_DESC: input.desc || '',
                BRANCH_TYPE: input.type || ResearchBranchModel.BRANCH_TYPE.FEATURE,
                PARENT_ID: input.parentId,
                BRANCH_STATUS: ResearchBranchModel.BRANCH_STATUS.ACTIVE,
                CREATOR_ID: userInfo.USER_ID,
                CREATOR_NAME: userInfo.USER_NAME,
                STATUS: 1, // 有效状态
                ADD_TIME: timeUtil.time(),
                EDIT_TIME: timeUtil.time()
            };
            
            // 插入分支记录
            const branchId = await branchModel.insert(data, transaction);
            
            // 复制父项目关键信息创建项目记录
            const projectData = {
                PROJECT_TITLE: parentProject.PROJECT_TITLE + ' - ' + input.name,
                PROJECT_CODE: parentProject.PROJECT_CODE + '-B' + Math.floor(Math.random() * 1000).toString().padStart(3, '0'),
                PROJECT_DESC: input.desc || parentProject.PROJECT_DESC,
                PROJECT_STATUS: parentProject.PROJECT_STATUS,
                PROJECT_ACTIVE_STATUS: parentProject.PROJECT_ACTIVE_STATUS,
                PROJECT_SUB_STATUS: parentProject.PROJECT_SUB_STATUS,
                PROJECT_MANAGER_ID: userInfo.USER_ID,
                PROJECT_MANAGER_NAME: userInfo.USER_NAME,
                IS_BRANCH: true,
                PARENT_ID: input.parentId,
                BRANCH_ID: branchId,
                STATUS: 1, // 有效状态
                ADD_TIME: timeUtil.time(),
                EDIT_TIME: timeUtil.time()
            };
            
            // 插入项目记录
            const projectId = await projectModel.insert(projectData, transaction);
            
            // 更新分支记录关联的项目ID
            await branchModel.edit(branchId, { PROJECT_ID: projectId }, transaction);
            
            // 提交事务
            await dbUtil.commitTransaction(transaction);
            
            // 记录系统日志
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: branchId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '创建分支',
                TYPE: 2, // 系统操作
                STATUS: 1, // 成功
                CONTENT: JSON.stringify({
                    parentId: input.parentId,
                    name: input.name,
                    desc: input.desc,
                    branchId: branchId,
                    projectId: projectId
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            return {
                _id: branchId,
                projectId: projectId,
                name: input.name
            };
        } catch (error) {
            console.error('创建项目分支失败:', error);
            
            // 回滚事务
            await dbUtil.rollbackTransaction(transaction);
            
            // 记录系统日志
            const userInfo = await this.getUserInfo();
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: '',
                MODEL_NAME: '研发项目分支',
                OPERATE: '创建分支',
                TYPE: 2, // 系统操作
                STATUS: 0, // 失败
                CONTENT: JSON.stringify({
                    parentId: input.parentId,
                    name: input.name,
                    desc: input.desc,
                    error: error.message || error.toString()
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            throw error;
        }
    }

    /**
     * 更新项目分支
     * @param {Object} input 请求参数
     */
    async updateBranch(input) {
        // 数据校验
        let rules = {
            branchId: 'must|string|name=分支ID',
            name: 'must|string|min:2|max:50|name=分支名称',
            desc: 'string|max:200|name=分支描述',
        };
        
        // 验证输入参数
        input = this.validateData(rules, input);
        
        console.log('更新项目分支', input);
        
        try {
            const userInfo = await this.getUserInfo();
            
            // 检查分支是否存在
            const branchModel = new ResearchBranchModel();
            const branch = await branchModel.getOne(input.branchId);
            
            if (!branch) {
                throw new Error('分支不存在');
            }
            
            // 更新分支数据
            const data = {
                BRANCH_NAME: input.name,
                BRANCH_DESC: input.desc || '',
                EDIT_TIME: timeUtil.time()
            };
            
            // 更新项目名称和描述
            if (branch.PROJECT_ID) {
                const projectModel = new ResearchProjectModel();
                await projectModel.edit(branch.PROJECT_ID, {
                    PROJECT_TITLE: branch.PROJECT_TITLE.replace(/\s-\s.*$/, '') + ' - ' + input.name,
                    PROJECT_DESC: input.desc || branch.PROJECT_DESC,
                    EDIT_TIME: timeUtil.time()
                });
            }
            
            // 执行更新
            await branchModel.edit(input.branchId, data);
            
            // 记录系统日志
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.branchId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '更新分支',
                TYPE: 2, // 系统操作
                STATUS: 1, // 成功
                CONTENT: JSON.stringify({
                    branchId: input.branchId,
                    name: input.name,
                    desc: input.desc
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            return { result: true };
        } catch (error) {
            console.error('更新项目分支失败:', error);
            
            // 记录系统日志
            const userInfo = await this.getUserInfo();
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.branchId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '更新分支',
                TYPE: 2, // 系统操作
                STATUS: 0, // 失败
                CONTENT: JSON.stringify({
                    branchId: input.branchId,
                    name: input.name,
                    desc: input.desc,
                    error: error.message || error.toString()
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            throw error;
        }
    }

    /**
     * 删除项目分支
     * @param {Object} input 请求参数
     */
    async deleteBranch(input) {
        // 数据校验
        let rules = {
            branchId: 'must|string|name=分支ID',
        };
        
        // 验证输入参数
        input = this.validateData(rules, input);
        
        console.log('删除项目分支', input);
        
        // 开启事务
        const transaction = await dbUtil.startTransaction();
        
        try {
            const userInfo = await this.getUserInfo();
            
            // 检查分支是否存在
            const branchModel = new ResearchBranchModel();
            const branch = await branchModel.getOne(input.branchId);
            
            if (!branch) {
                throw new Error('分支不存在');
            }
            
            // 检查分支状态，如果是已合并状态则不允许删除
            if (branch.BRANCH_STATUS === ResearchBranchModel.BRANCH_STATUS.MERGED) {
                throw new Error('已合并的分支不能删除，请先解除合并状态');
            }
            
            // 更新分支状态为删除
            await branchModel.edit(input.branchId, {
                BRANCH_STATUS: ResearchBranchModel.BRANCH_STATUS.ABANDONED,
                STATUS: 0, // 无效状态
                EDIT_TIME: timeUtil.time()
            }, transaction);
            
            // 如果有关联项目，删除项目
            if (branch.PROJECT_ID) {
                const projectModel = new ResearchProjectModel();
                await projectModel.edit(branch.PROJECT_ID, {
                    STATUS: 0, // 无效状态
                    EDIT_TIME: timeUtil.time()
                }, transaction);
            }
            
            // 提交事务
            await dbUtil.commitTransaction(transaction);
            
            // 记录系统日志
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.branchId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '删除分支',
                TYPE: 2, // 系统操作
                STATUS: 1, // 成功
                CONTENT: JSON.stringify({
                    branchId: input.branchId,
                    projectId: branch.PROJECT_ID
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            return { result: true };
        } catch (error) {
            console.error('删除项目分支失败:', error);
            
            // 回滚事务
            await dbUtil.rollbackTransaction(transaction);
            
            // 记录系统日志
            const userInfo = await this.getUserInfo();
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.branchId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '删除分支',
                TYPE: 2, // 系统操作
                STATUS: 0, // 失败
                CONTENT: JSON.stringify({
                    branchId: input.branchId,
                    error: error.message || error.toString()
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            throw error;
        }
    }

    /**
     * 合并项目分支
     * @param {Object} input 请求参数
     */
    async mergeBranch(input) {
        // 数据校验
        let rules = {
            sourceId: 'must|string|name=源分支ID',
            targetId: 'must|string|name=目标项目ID',
        };
        
        // 验证输入参数
        input = this.validateData(rules, input);
        
        console.log('合并项目分支', input);
        
        // 开启事务
        const transaction = await dbUtil.startTransaction();
        
        try {
            const userInfo = await this.getUserInfo();
            
            // 检查源分支是否存在
            const branchModel = new ResearchBranchModel();
            const sourceBranch = await branchModel.getOne(input.sourceId);
            
            if (!sourceBranch) {
                throw new Error('源分支不存在');
            }
            
            // 检查目标项目是否存在
            const projectModel = new ResearchProjectModel();
            const targetProject = await projectModel.getOne(input.targetId);
            
            if (!targetProject) {
                throw new Error('目标项目不存在');
            }
            
            // 检查源分支状态，不能是已合并或已废弃状态
            if (sourceBranch.BRANCH_STATUS === ResearchBranchModel.BRANCH_STATUS.MERGED) {
                throw new Error('分支已经合并，不能重复合并');
            }
            
            if (sourceBranch.BRANCH_STATUS === ResearchBranchModel.BRANCH_STATUS.ABANDONED) {
                throw new Error('分支已废弃，不能进行合并');
            }
            
            // 创建合并记录
            const mergeData = {
                SOURCE_BRANCH_ID: input.sourceId,
                TARGET_PROJECT_ID: input.targetId,
                MERGE_STATUS: 1, // 合并成功
                CONFLICT_STATUS: 0, // 无冲突
                MERGER_ID: userInfo.USER_ID,
                MERGER_NAME: userInfo.USER_NAME,
                MERGE_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time(),
                EDIT_TIME: timeUtil.time()
            };
            
            // 插入合并记录（此处简化处理，实际应该有专门的合并表）
            await branchModel.insertDirect('research_project_branch_merge', mergeData, transaction);
            
            // 更新分支状态为已合并
            await branchModel.edit(input.sourceId, {
                BRANCH_STATUS: ResearchBranchModel.BRANCH_STATUS.MERGED,
                MERGE_TARGET_ID: input.targetId,
                MERGE_TIME: timeUtil.time(),
                EDIT_TIME: timeUtil.time()
            }, transaction);
            
            // 提交事务
            await dbUtil.commitTransaction(transaction);
            
            // 记录系统日志
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.sourceId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '合并分支',
                TYPE: 2, // 系统操作
                STATUS: 1, // 成功
                CONTENT: JSON.stringify({
                    sourceId: input.sourceId,
                    targetId: input.targetId
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            return { result: true };
        } catch (error) {
            console.error('合并项目分支失败:', error);
            
            // 回滚事务
            await dbUtil.rollbackTransaction(transaction);
            
            // 记录系统日志
            const userInfo = await this.getUserInfo();
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.sourceId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '合并分支',
                TYPE: 2, // 系统操作
                STATUS: 0, // 失败
                CONTENT: JSON.stringify({
                    sourceId: input.sourceId,
                    targetId: input.targetId,
                    error: error.message || error.toString()
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            throw error;
        }
    }

    /**
     * 获取分支版本历史
     * @param {Object} input 请求参数
     */
    async getBranchVersions(input) {
        // 数据校验
        let rules = {
            branchId: 'must|string|name=分支ID',
        };
        
        // 验证输入参数
        input = this.validateData(rules, input);
        
        console.log('获取分支版本历史', input);
        
        try {
            const userInfo = await this.getUserInfo();
            
            // 检查分支是否存在
            const branchModel = new ResearchBranchModel();
            const branch = await branchModel.getOne(input.branchId);
            
            if (!branch) {
                throw new Error('分支不存在');
            }
            
            // 查询版本历史
            const versionModel = new ResearchVersionModel();
            const where = {
                BRANCH_ID: input.branchId,
                STATUS: 1 // 有效状态
            };
            
            const list = await versionModel.getList(where, 'VERSION_NUM DESC');
            
            // 格式化结果
            const result = list.map(item => {
                return {
                    _id: item._id,
                    VERSION: item.VERSION_NUM,
                    TITLE: item.VERSION_TITLE,
                    DESC: item.VERSION_DESC,
                    BRANCH_ID: item.BRANCH_ID,
                    CREATOR_ID: item.CREATOR_ID,
                    CREATOR_NAME: item.CREATOR_NAME,
                    ACTIVE: item.IS_ACTIVE === 1,
                    ADD_TIME: item.ADD_TIME,
                    EDIT_TIME: item.EDIT_TIME
                };
            });
            
            // 记录系统日志
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.branchId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '获取版本历史',
                TYPE: 2, // 系统操作
                STATUS: 1, // 成功
                CONTENT: JSON.stringify({
                    branchId: input.branchId,
                    versionCount: result.length
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            return result;
        } catch (error) {
            console.error('获取分支版本历史失败:', error);
            
            // 记录系统日志
            const userInfo = await this.getUserInfo();
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.branchId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '获取版本历史',
                TYPE: 2, // 系统操作
                STATUS: 0, // 失败
                CONTENT: JSON.stringify({
                    branchId: input.branchId,
                    error: error.message || error.toString()
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            throw error;
        }
    }

    /**
     * 切换到指定版本
     * @param {Object} input 请求参数
     */
    async switchToVersion(input) {
        // 数据校验
        let rules = {
            branchId: 'must|string|name=分支ID',
            versionId: 'must|string|name=版本ID',
        };
        
        // 验证输入参数
        input = this.validateData(rules, input);
        
        console.log('切换到指定版本', input);
        
        // 开启事务
        const transaction = await dbUtil.startTransaction();
        
        try {
            const userInfo = await this.getUserInfo();
            
            // 检查分支是否存在
            const branchModel = new ResearchBranchModel();
            const branch = await branchModel.getOne(input.branchId);
            
            if (!branch) {
                throw new Error('分支不存在');
            }
            
            // 检查版本是否存在
            const versionModel = new ResearchVersionModel();
            const version = await versionModel.getOne(input.versionId);
            
            if (!version) {
                throw new Error('版本不存在');
            }
            
            // 确认版本属于该分支
            if (version.BRANCH_ID !== input.branchId) {
                throw new Error('版本不属于当前分支');
            }
            
            // 将所有版本设为非活动
            await versionModel.editBatch({
                BRANCH_ID: input.branchId
            }, {
                IS_ACTIVE: 0,
                EDIT_TIME: timeUtil.time()
            }, transaction);
            
            // 将当前版本设为活动
            await versionModel.edit(input.versionId, {
                IS_ACTIVE: 1,
                EDIT_TIME: timeUtil.time()
            }, transaction);
            
            // 更新分支的当前版本
            await branchModel.edit(input.branchId, {
                CURRENT_VERSION_ID: input.versionId,
                CURRENT_VERSION: version.VERSION_NUM,
                EDIT_TIME: timeUtil.time()
            }, transaction);
            
            // 提交事务
            await dbUtil.commitTransaction(transaction);
            
            // 记录系统日志
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.versionId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '切换版本',
                TYPE: 2, // 系统操作
                STATUS: 1, // 成功
                CONTENT: JSON.stringify({
                    branchId: input.branchId,
                    versionId: input.versionId,
                    versionNum: version.VERSION_NUM
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            return { result: true };
        } catch (error) {
            console.error('切换到指定版本失败:', error);
            
            // 回滚事务
            await dbUtil.rollbackTransaction(transaction);
            
            // 记录系统日志
            const userInfo = await this.getUserInfo();
            await LogModel.insert({
                USER_ID: userInfo.USER_ID,
                USER_NAME: userInfo.USER_NAME,
                MODEL_ID: input.versionId,
                MODEL_NAME: '研发项目分支',
                OPERATE: '切换版本',
                TYPE: 2, // 系统操作
                STATUS: 0, // 失败
                CONTENT: JSON.stringify({
                    branchId: input.branchId,
                    versionId: input.versionId,
                    error: error.message || error.toString()
                }),
                EDIT_TIME: timeUtil.time(),
                ADD_TIME: timeUtil.time()
            });
            
            throw error;
        }
    }
}

module.exports = ResearchBranchController; 